package com.atguigu.service.impl;

import com.atguigu.dao.BookDao;
import com.atguigu.dao.OrderDao;
import com.atguigu.dao.OrderItemDao;
import com.atguigu.dao.impl.BaseDao;
import com.atguigu.dao.impl.BookDaoImpl;
import com.atguigu.dao.impl.OrderDaoImpl;
import com.atguigu.dao.impl.OrderItemDaoImpl;
import com.atguigu.pojo.*;
import com.atguigu.service.OrderService;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class OrderServiceImpl implements OrderService {
    private OrderDao orderDao = new OrderDaoImpl();
    private OrderItemDao orderItemDao = new OrderItemDaoImpl();
    private BookDao bookDao = new BookDaoImpl();

    /**
     * 生成订单和订单项
     *
     * @param cart
     * @param userId
     */
    @Override
    public String createOrder(Cart cart, Integer userId) {
        //保存订单
        String orderId = System.currentTimeMillis() + "" + userId;
        Order order = new Order(orderId, new Date(), cart.getTotalPrice(), 0, userId);
        orderDao.saveOrder(order);
        //保存订单项  需要循环遍历购物车中的商品项
        Set<Map.Entry<Integer, CartItem>> entries = cart.getItems().entrySet();
        for (Map.Entry<Integer, CartItem> entry : entries) {
            CartItem value = entry.getValue();
            OrderItem orderItem = new OrderItem(null, value.getName(), value.getCount(), value.getPrice(), value.getTotalPrice(), orderId);
            orderItemDao.saveOrderItem(orderItem);

            //更新库存和销量
            Book book = bookDao.queryBookById(value.getId());

            book.setSales(book.getSales() + value.getCount());
            book.setStock(book.getStock() - value.getCount());
            bookDao.upadateBook(book);
        }
        //清空购物车
        cart.clear();
        return orderId;
    }

    /**
     * 展现所有的订单项
     *
     * @return
     */
    @Override
    public List<Order> showAllOrders() {
        List<Order> orders = orderDao.queryOrders();
        return orders;
    }

    /**
     * 发货
     *
     * @param orderId
     */
    @Override
    public int sendOrder(String orderId) {
        int i = orderDao.changeStatus(orderId, 1);
        return i;
    }

    @Override
    public List<Order> showMyOrder(Integer userId) {
        List<Order> orders = orderDao.queryOrdersByUserId(userId);
        return orders;
    }

    /**
     * 查看订单项详情
     *
     * @param orderId
     * @return
     */
    @Override
    public List<OrderItem> showOrderDetail(String orderId) {
        List<OrderItem> orderItems = orderItemDao.queryOrderItemsByOrderId(orderId);
        return orderItems;
    }

    /**
     * 收获
     * @param orderId
     * @return
     */
    @Override
    public int receiverOrder(String orderId) {
        int i = orderDao.changeStatus(orderId, 2);
        return i;
    }
}
